/**
 * @description 生成对应schema验证器的中间件
 * @author malin
 */

const { ErrorModel } = require('../model/ResModel')
const { jsonSchemaValidateFailed } = require('../model/ErrorInfo')

/**
 * 生成对应schema验证器的中间件
 * @param {function} validateFn 
 */
function genValidator(validateFn) {
    async function validatorMidw(ctx, next) {
        const data = ctx.request.body
        let errors = validateFn(data)
        if (errors) {
            ctx.body = new ErrorModel(jsonSchemaValidateFailed)
            return
        }
        // 验证成功，向下走
        await next()
    }
    return validatorMidw
}

module.exports = genValidator
